package com.chengzhi.eshopinventory.thread;

import com.chengzhi.eshopinventory.request.BaseRequest;
import com.chengzhi.eshopinventory.request.InventoryQueryRequest;
import com.chengzhi.eshopinventory.request.InventoryUpdateRequest;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description
 * @author: ruanchengzhi
 * @create: 2021-04-01 15:43
 **/
public class WorkerThread implements Callable<Boolean> {
    ArrayBlockingQueue<BaseRequest> blockingQueue;

    public WorkerThread(ArrayBlockingQueue<BaseRequest> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    /**
     * 从队列中获取数据进行消费
     *
     * @param
     * @return java.lang.Boolean
     * @throws
     * @author ruanchengzhi
     * @date 2021/4/1
     */
    @Override
    public Boolean call() throws Exception {
        try {
            while (true) {
                BaseRequest request = blockingQueue.take();
                boolean forcedRefresh = request.isForcedRefresh();
                if (!forcedRefresh) {
                    Long inventoryId = request.getInventoryId();
                    ConcurrentHashMap<Long, Boolean> flagMap = RequestThreadPool.getInstance().getFlagMap();
                    //读请求去重
                    if (request instanceof InventoryUpdateRequest) {
                        flagMap.put(inventoryId, Boolean.TRUE);
                    } else if (request instanceof InventoryQueryRequest) {
                        Boolean flag = flagMap.get(inventoryId);
                        if (null != flag && flag) {
                            flagMap.put(inventoryId, Boolean.FALSE);
                        }
                        if (null != flag && !flag) {
                            return true;
                        }
                        //空数据读请求优化
                        if (flag == null) {
                            flagMap.put(inventoryId, Boolean.FALSE);
                        }
                    }
                }
                request.execute();
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return false;
        }
    }
}
